package net.aiion.weave.impl.xml;

import java.util.Objects;

import net.aiion.weave.spi.xml.XmlQualifiedName;

public class XmlQualifiedNameImpl implements XmlQualifiedName
{
    private static final String TO_STRING_FORMAT_PATTERN = "%s:%s";

    private final String xmlPrefix;
    private final String xmlNamespaceURI;
    private final String xmlLocalName;

    public XmlQualifiedNameImpl(final String aLocalName) {
        this("", aLocalName, "");
    }

    public XmlQualifiedNameImpl(final String aNamespaceURI, final String aLocalName) {
        this(aNamespaceURI, aLocalName, "");
    }

    public XmlQualifiedNameImpl(final String aNamespaceURI, final String aLocalName, final String aPrefix) {
        xmlPrefix = aPrefix;
        xmlNamespaceURI = aNamespaceURI;
        xmlLocalName = aLocalName;
    }

    @Override
    public String getPrefix() {
        return xmlPrefix;
    }

    @Override
    public String getNamespaceURI() {
        return xmlNamespaceURI;
    }

    @Override
    public String getLocalName() {
        return xmlLocalName;
    }

    @Override
    public String toShortString() {
        return String.format(TO_STRING_FORMAT_PATTERN, xmlPrefix, xmlLocalName);
    }

    @Override
    public String toLongString() {
        return String.format(TO_STRING_FORMAT_PATTERN, xmlNamespaceURI, xmlLocalName);
    }

    @Override
    public int hashCode() {
        int result = 7;
        result = 61 * result + Objects.hashCode(xmlLocalName);
        result = 61 * result + Objects.hashCode(xmlNamespaceURI);
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof XmlQualifiedNameImpl)) {
            return false;
        }
        final XmlQualifiedNameImpl other = (XmlQualifiedNameImpl) obj;
        if (!Objects.equals(xmlLocalName, other.xmlLocalName)) {
            return false;
        }
        if (!Objects.equals(xmlNamespaceURI, other.xmlNamespaceURI)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        if (xmlNamespaceURI == null) {
            return xmlLocalName;
        }

        if (xmlPrefix == null) {
            return String.format(TO_STRING_FORMAT_PATTERN, xmlNamespaceURI, xmlLocalName);
        }

        return String.format("%s[%s]:%s", xmlPrefix, xmlNamespaceURI, xmlLocalName);
    }
}
